import sys
import os
import re

from importlib.machinery import SourceFileLoader

thisDir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(thisDir, "..", "..", "common"))
sys.path.append(os.path.join(thisDir, "..", "..", "server"))

import EJOConfig

from EJOHandlerBase import EJOHandlerBase

import logging
logger = logging.getLogger(__name__)

def InitAPIHandler():
    handlerDir = os.path.join(thisDir, "..", "..", "server", "handlers")
    passed = True
    for handlerFile in os.listdir(handlerDir):
        passed = False
        logger.debug(f"[test.handler] Handle File: {handlerFile}")
        print(f"[test.handler] Handle File: {handlerFile}")
        try:
            handlerPath = os.path.join(handlerDir, handlerFile)
            if os.path.isfile(handlerPath) and re.match("^[\\w]+\\.py$", handlerFile):
                handlerName = handlerFile[0:-3]
                handlerModule = SourceFileLoader(handlerName, handlerPath).load_module()
                handler = getattr(handlerModule, handlerName)
                if handler:
                    if issubclass(handler, EJOHandlerBase):
                        logger.debug(f"[test.handler] Successful: {handlerName}")
                        print(f"[test.handler] Successful: {handlerName}")
                    else:
                        logger.debug(f"[test.handler] Handler is not subclass of EJOHandlerBase: {handler}")
                        print(f"[test.handler] Handler is not subclass of EJOHandlerBase: {handler}")
                        return passed
                else:
                    logger.debug(f"[test.handler] Handler is not loaded: {handlerFile}")
                    print(f"[test.handler] Handler is not loaded: {handlerFile}")
                    return passed
            passed = True
        except Exception as e:
            logger.debug(f"[test.handler] Handler file loading exception: {handlerFile}")
            print(f"[test.handler] Handler file loading exception: {handlerFile}")
            logger.debug(e)
            print(e)
            return False
        logger.debug(f"[test.handler] Handle Finished: {handlerFile}")
        print(f"[test.handler] Handle Finished: {handlerFile}")
    return passed

def Start():
    logger.debug("[test.handler] Start")
    print("[test.handler] Start")

    if InitAPIHandler():
        logger.debug("[test.handler] Initialize handler pass")
        print("[test.handler] Initialize handler pass")
    else:
        logger.debug("[test.handler] Initialize handler fail")
        print("[test.handler] Initialize handler fail")

    logger.debug("[test.handler] End")
    print("[test.handler] End")

if __name__ == "__main__":
    logging.basicConfig(filename = EJOConfig.TEST_LOG_PATH, level = EJOConfig.TEST_LOG_LEVEL)
    Start()
